package com.itheima.webSocket;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.entity.AccountAuthentication;
import com.itheima.entity.AccountMessage;
import com.itheima.entity.ProjectReview;
import com.itheima.mapper.AccountAuthenticationMapper;
import com.itheima.mapper.AccountMessageMapper;
import com.itheima.service.impl.AccountAuthenticationServiceImpl;
import com.itheima.service.impl.ProjectReviewProgressServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import org.springframework.web.socket.handler.WebSocketSessionDecorator;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
public class AccountAuthenticationWebSocketHandler extends TextWebSocketHandler {
    private ObjectMapper objectMapper = new ObjectMapper();
    // 注入CommentsServiceImpl
    private final AccountAuthenticationServiceImpl authenticationService;
    private final AccountAuthenticationMapper messageMapper;
    @Autowired
    public AccountAuthenticationWebSocketHandler(AccountAuthenticationServiceImpl authenticationService,
                                                 AccountAuthenticationMapper messageMapper) {
        this.authenticationService = authenticationService;
        this.messageMapper = messageMapper;
    }
    // 定义sessions集合，用于存放所有连接到WebSocket的客户端session
    private static final CopyOnWriteArraySet<WebSocketSession> sessions = new CopyOnWriteArraySet<>();
    // 存放用户id和session的映射关系
    private static final Map<String, WebSocketSession> userSessions = new HashMap<>();
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.println("账户消息客户端连接成功：" + session.getId());
        // 解析请求参数，获取用户id
        // 获取用户id
        String userId = session.getUri().getPath().substring(session.getUri().getPath().lastIndexOf('/') + 1);
        // 将用户id和session添加到map中
        System.out.println("用户id：" + userId);
       // 判断是否已经有该用户的session
        if (!userSessions.containsKey(userId)) {
            userSessions.put(userId, session);
            // 存放session到sessions集合中
            sessions.add(session);
        }
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 接收并处理客户端消息
        System.out.println("接收到消息：" + message.getPayload());
        AccountAuthentication authentication = objectMapper.readValue(message.getPayload(), AccountAuthentication.class);
        // 保存消息到数据库
        AccountMessage messag = new AccountMessage();
        authenticationService.insertAccountAuthentication(authentication);
        //新增管理员消息
        List<Long> adminIds = messageMapper.selectAdminIds();
        messag.setTitle("有新的 "+authentication.getUsername()+" 用户提交了认证申请");
        messag.setDescription("请及时查看审核！");
        messag.setType(2L);
        messag.setStatus("info");
        messag.setIsRead(0L);
        messag.setExtra("待审核");
        for (Long id : adminIds) {
            // 判断是否需要发送消息给特定用户
            WebSocketSession targetSession = userSessions.get(String.valueOf(id));
            if (targetSession != null && targetSession.isOpen()) {
                // 转换成json字符串
                String dataJson = objectMapper.writeValueAsString(messag);
                // 发送消息给特定用户
                targetSession.sendMessage(new TextMessage(dataJson));
            }
        }

    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        System.out.println("账户消息客户端断开连接：" + session.getId());
        // 移除用户id和session的映射关系
        // 获取用户id
        String userId = session.getUri().getPath().substring(session.getUri().getPath().lastIndexOf('/') + 1);
        // 从map中移除用户id对应的session
        userSessions.remove(userId);
        // 移除session
        sessions.remove(session);
    }
}
